package com.example.emos.wx.config.shiro;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.emos.wx.exception.EmosException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * JwtUtil工具类
 * @author liujingmao
 * @version 1.0
 * @date 2021/1/31 17:14
 */
@Component
@Slf4j
public class JwtUtil {

    //密钥
    @Value("${emos.jwt.secret}")
    private String secret;

    //
    @Value("${emos.jwt.expire}")
    private int expire;

    /*emos:
    jwt:
            #密钥
    secret: abc123456
    #令牌过期时间（天）
    expire:  5
            #令牌缓存时间（天数）
    cache-expire: 10*/

    /**
     * 根据用户id创建token
     * @param userId
     * @return
     */
    public String createToken(int userId){
        Date date = DateUtil.offset(new Date(), DateField.DAY_OF_YEAR,expire).toJdkDate();
        //创建加密算法对象
        Algorithm algorithm = Algorithm.HMAC256(secret);
        JWTCreator.Builder builder = JWT.create();
        String token = builder.withClaim("userId",userId)
                .withExpiresAt(date).sign(algorithm);
        return token;
    }

    /**
     * 根据token获取UserId
     * @param token
     * @return
     */
    public int getUserId(String token){
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("userId").asInt();

        } catch (Exception e){
            throw  new EmosException("令牌token无效");
        }
    }

    public void verifierToken(String toekn){

        Algorithm algorithm = Algorithm.HMAC256(secret);
        JWTVerifier verifier = JWT.require(algorithm).build();
        verifier.verify(toekn);

    }


}
